#include "lwip/api.h"
#include "ethuser.h"

static struct netconn* _netconn  = NULL;

void test_eth_user_sned(void *pvParameters);

int ethuser_init(void)
{
   _netconn = netconn_new(NETCONN_TCP);
	if(!_netconn)
	{
		printf("netconn_new failed\r\n");
		return 0;
	}
	else
	{
 	printf("netconn new success\r\n");
	}		
	err_t err;
	ip_addr_t ipaddr;
	IP4_ADDR(&ipaddr,192,168,1,33);      //服务器IP地址
	err = netconn_connect(_netconn, &ipaddr,8001);
  if(err != ERR_OK)
	{
		  printf("netconn_connect failed\r\n");
		  netconn_delete(_netconn);
		  _netconn= NULL;
		  return 0;
	}
	else
	{
 	   printf(" netconn_connect success\r\n");
	}
	return 1;

}

void eth_user_task(void *pvParameters) 
{
	
	struct  pbuf  *p = NULL;
	err_t err;
	while(ethuser_init() != 1)
	{
		;
	}
	//xTaskCreate(test_eth_user_sned,                   (const char *)"test_eth_user_sned",        configMINIMAL_STACK_SIZE ,         NULL,   2,       NULL);
  while(1)
	{					 
		  err =netconn_recv_tcp_pbuf(_netconn,&p);
			if(err == ERR_OK)
			{									  			 	 			 
			  printf("recv len = %d data:%s\r\n", p->len,p->payload);			
        				
			}		 
			else if (err == ERR_CLSD || err != ERR_RST)
			{				
				 printf("netconn_recv_tcp_pbuf faile err = %d\r\n",err);		 	 
			}
			pbuf_free(p);
      p = NULL;
    	   
		  vTaskDelay(10 / portTICK_RATE_MS);
		}	
	
}
void eth_user_send(uint8_t *buf,uint32_t len) 
{
	
   err_t err =netconn_write(_netconn,buf,strlen((char_t *)buf),0);
	 if(err != ERR_OK)
	 {
		  printf("eth_user_send failed\r\n");
	 }
}

#if 0
#include "rtc.h"
void test_eth_user_sned(void *pvParameters) 
{
	T_CalendarObj obj;
	char buf[100] = {0};
	
	
	while(1)
	{
	  RTC_GetTimeNow(&obj);		
		
		sprintf(buf,"%d-%d-%d %d:%d:%d",obj.Date.RTC_Year,obj.Date.RTC_Month,obj.Date.RTC_Date,obj.Time.RTC_Hours,obj.Time.RTC_Minutes,obj.Time.RTC_Seconds);
		eth_user_send(buf,strlen(buf));
		vTaskDelay(1000 / portTICK_RATE_MS);
	}
}
#endif





